<?php
/*
 * Created on 20.04.2008
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
 
 define ('MODEL_GOOD_FIND',						'SELECT * FROM `goods` WHERE `id` = ? AND `type` = \'good\'');
 define ('MODEL_GOOD_FIND_LIMIT',				'SELECT * FROM `goods` WHERE `sex` = :sex AND `type` = \'good\' LIMIT :start, :count'); 
 define ('MODEL_GOOD_GET_CATEGORIES',			'SELECT * FROM `goods_categories` WHERE `sex` = ? ORDER BY `order_id` ');
 define ('MODEL_GOOD_GET_ALL_CATEGORIES',       'SELECT `id`,`name` FROM `goods_categories` ORDER BY `order_id` ');
 define ('MODEL_GOOD_FIND_CATEGORY_BY_ALIAS',	'SELECT `goods`. * FROM `goods` , `goods_categories` WHERE `goods`.`category` = `goods_categories`.`id` AND `goods_categories`.`alias` = :alias AND `type` = \'good\' AND `status` = 1 LIMIT :start, :count');
 define ('MODEL_GOOD_FIND_CATEGORY',			'SELECT * FROM `goods` WHERE `category` = :category AND `type` = \'good\' LIMIT :start, :count');
 
 define ('MODEL_GOOD_ADD',				'INSERT INTO `goods` (`id` ,`name` ,`description` ,`price` ,`category` ,`art` ,`structure` ,`sex` ,`size` ,`color`,`exists`) VALUES (NULL , ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )');
 define ('MODEL_GOOD_SAVE',				'UPDATE `goods` SET `name` = ?, `description` = ?, `price` = ?, `category` = ?, `art` = ?, `sex` = ?, `size` = ?, `color` = ?, `exists`=?, `structure`=? WHERE `id` = ? ');
 define ('MODEL_GOOD_ADD_CATEGORY',		'INSERT INTO `goods_categories` (`id` ,`name` ,`order_id`, `sex`, `alias`) VALUES (NULL , ?, "", ?, ?)');
 define	('MODEL_GOOD_DELETE_CATEGORY',	'DELETE FROM `goods_categories` WHERE `id` = ?');
 define ('MODEL_GOOD_DELETE',			'DELETE FROM `goods` WHERE `id` = ?');
 
 define ('MODEL_GOOD_CLEAR_RESTS',		'UPDATE `goods` SET `exists` = 0');
 define ('MODEL_GOOD_UPDATE_REST',		'UPDATE `goods` SET `exists` = 1 WHERE `art` = ?');
 
 define ('MODEL_GOOD_GET_IMAGES',		'SELECT `pimg` FROM `goods` WHERE `parent_id` = ? ORDER BY `name`');
 
 
 define ('MODEL_GOOD_COUNT',			'SELECT count(*) as count FROM `goods` , `goods_categories` WHERE `goods`.`category` = `goods_categories`.`id` AND `goods_categories`.`alias` = ? AND `type` = \'good\' ');
 
 define ('MODEL_GOOD_SEARCH',           "SELECT * FROM `goods` WHERE `name` LIKE '%k%'");
 
 class Model_Good extends Models_Base {
 	
 	private $good;
 	
 	function __construct( $id= null ) {
 		parent::__construct();
 	
 		if ($id)
 			$this->good = $this->find(array(id => $id));
 	}
 	
 	function add($args) {
 		if(empty($args[name])) 
 			throw new GoodsException('empty_name');

 		if(empty($args[description])) 
 			throw new GoodsException('empty_description');
 			
 		if(empty($args[code])) 
 			throw new GoodsException('empty_code');
 			
 		if(empty($args[price])) 
 			throw new GoodsException('empty_price');
 			
 		if(empty($args[size])) 
 			throw new GoodsException('empty_size');

 		if(empty($args[color])) 
 			throw new GoodsException('empty_color');

		$size = new Model_Size();
		$size = $size->getMaskByList($args[size]);
		
		$color = new Model_Color();
		$color->getList();
		$color = $color->getMaskByList($args[color]);
		
//		$structure = new Model_Structure();
//		$structure->getList();
//		$structure = $structure->getMaskByList($args[structure]);
//		error_log(MODEL_GOOD_ADD);
//		error_log("EXIST: ")
		$this->insertRow(MODEL_GOOD_ADD,array($args[name],$args[description],$args[price],$args[category],$args[code],$args[structure],$args[sex],$size,$color,$args[exists])); 			 			
 		
 	}

 	function save($args) {

 		if(empty($args[id])) 
 			throw new GoodsException('empty_id');
 		
 		if(empty($args[name])) 
 			throw new GoodsException('empty_name');

 		if(empty($args[description])) 
 			throw new GoodsException('empty_description');
 			
 		if(empty($args[code])) 
 			throw new GoodsException('empty_code');
 			
 		if(empty($args[price])) 
 			throw new GoodsException('empty_price');
 			
 		if(empty($args[size])) 
 			throw new GoodsException('empty_size');

 		if(empty($args[color])) 
 			throw new GoodsException('empty_color');



		
//		$structure = new Model_Structure();
//		$structure->getList();
//		$structure = $structure->getMaskByList($args[structure]);
//print "<pre>";
//print_r($structure);
////print_r(array($args[size], $args[color], $args[structure]));
////print_r(array($size, $color,$structure));
//print "</pre>"; 			
		//'UPDATE `goods` SET `name` = ?, `description` = ?, `price` = ?, `category` = ?, `art` = ?, `sex` = ?, `size` = ?, `color` = ?, `exists` = ? WHERE `id` = ? ' 
		$this->insertRow(MODEL_GOOD_SAVE,array($args[name],$args[description],$args[price],$args[category],$args[code],$args[sex],$size,$color,$args[exists],$args[structure],$args[id])); 			 			
 		
 	}
 	
 	function find($args = null) {
 		
 		if (empty($args[from])) 
 			$start = 0;
 
  		if (empty($args[limit])) 
 			$count = 5000;			
 		
 		if(isset($args[id])) {
 			return $this->getRow(MODEL_GOOD_FIND,array($args[id]));
 		} else if($args[category]) {
 			return $this->findCategory($args[category],$start, $count);
 		} else if($args[category_alias]) {
 			
 			$page = $args[page] ? $args[page] : 1;
 			
 			$start = ($page-1) * GOODS_PER_PAGE;	
 		
 			return $this->findCategoryByAlias($args[category_alias],$start, GOODS_PER_PAGE);

 		} else {
 			return $this->findLimited($args[sex], $start, $count);
 		}
 		

 	}
 	
 	private function findCategory($category, $start, $count) {
 		$sth = $this->dbh->prepare(MODEL_GOOD_FIND_CATEGORY);

 		if(empty($start))
 			$start = 0;
 		if(empty($count))
 			$count = 30;
 		
 		$sth->bindValue(':category',$category,PDO::PARAM_INT);
 		$sth->bindValue(':start',$start,PDO::PARAM_INT);
 		$sth->bindValue(':count',$count,PDO::PARAM_INT);
 		
 		$sth->execute();
 		
 		return $sth->fetchAll(); 		
 	}
 	private function findCategoryByAlias($alias, $start, $count) {
 		$sth = $this->dbh->prepare(MODEL_GOOD_FIND_CATEGORY_BY_ALIAS);

 		if(empty($start))
 			$start = 0;
 		if(empty($count))
 			$count = 30;
 		
 		$sth->bindValue(':alias',$alias,PDO::PARAM_STR);
 		$sth->bindValue(':start',$start,PDO::PARAM_INT);
 		$sth->bindValue(':count',$count,PDO::PARAM_INT);
 		
 		$sth->execute();
 		
 		return $sth->fetchAll(); 		
 	} 	
 	
 	private function findLimited ($sex, $start, $count) {
 		$sth = $this->dbh->prepare(MODEL_GOOD_FIND_LIMIT);
//error_log(MODEL_GOOD_FIND_LIMIT);
//error_log("$sex | | $start | $count");
		$sth->bindValue(':sex', $sex, PDO::PARAM_INT);
 		$sth->bindValue(':start', $start, PDO::PARAM_INT);
 		$sth->bindValue(':count', $count, PDO::PARAM_INT);
 		
 		$sth->execute();
 		
 		return $sth->fetchAll();
 		
 	}
 	
 	function getCategories($sex = null) {
 		
 	    if($sex != null)
            return $this->getAll(MODEL_GOOD_GET_CATEGORIES,array($sex));
        else
            return $this->getAll(MODEL_GOOD_GET_ALL_CATEGORIES);
 	}
 	
 	function addCategory($name,$sex,$alias) {
 		$this->insertRow(MODEL_GOOD_ADD_CATEGORY,array($name,$sex,$alias));
 	}
 	
 	function deleteCategory($id) {
 		$this->execute(MODEL_GOOD_DELETE_CATEGORY,array($id));
 	}
 	
 	function getList($list) {
 		
 		if($list) {
	 		$sth = $this->dbh->prepare(MODEL_GOOD_FIND);
	 		
	 		foreach($list as $item) {
	 			$sth->execute(array($item[id]));
	 			$out[] = array($item[quantity],$sth->fetchObject(),count($item[colors]),$item[sizes],$item[colors], $item[in_suit]);
	 		}
 		}
 		
 		return $out;
 	}
 	
 	function delete($id) {
 		$this->execute(MODEL_GOOD_DELETE,array($id));
 	}
 	
 	function loadRests($data) {
 		$this->execute(MODEL_GOOD_CLEAR_RESTS);
 		

 		
 		$sth = $this->dbh->prepare(MODEL_GOOD_UPDATE_REST);
 		
 		foreach($data as $key => $value) {
 			 if(count($value) == 5) {

 				$sth->execute(array($value[1])); 	
 			 } 
 		}
 		
 	}
 	
 	function getImages($args) {
 		
 		if(gettype($args) == 'array') {
 			
 			
 			$images = array();
 			
 			foreach ($args as $id) {
 				$images[$id] = $this->getImages($id);
 			}	
 		
 			return $images;
 		} else {
 			return $this->getAll(MODEL_GOOD_GET_IMAGES,array($args));	
 		}
		
 	}
 	
 	function getPages($alias) {
 		$count = $this->getRow(MODEL_GOOD_COUNT,array($alias));

		$pages = array();

		for( $i = $count->count / GOODS_PER_PAGE; $i >0 ;$i-- ){
			$pages[] = ceil($i);
		}
		sort ($pages);
 		
 		return count($pages) > 1 ? $pages : false;
 	}
 	
    function search($args) {
    	
        $sql = 'SELECT `goods`.* , `goods_categories`.`alias` FROM `goods`,`goods_categories` WHERE ';
        
        $where = array();

        if($args['type'])
            $where[] = " `goods`.`category` = '$args[type]' ";


        if($args['string'])
            $where[] = " `goods`.`name` LIKE '%$args[string]%' ";

        if($args['region'])
            $where[] = " `goods`.`city` = '$args[region]' ";

        if($args['price']) {
        	
        
            $where[] = " $args[price] ";
        }

//        $where[] = " `goods`.`name` LIKE '%$args[string]%' ";
        $where[] = " `goods`.`type` = 'good' ";
        $where[] = " `goods`.`status` = 1 ";
        $where[] = " `goods`.`status` = 1 ";
        $where[] = " `goods`.`category` = `goods_categories`.`id` ";
        
        $sql .= join(' AND ',$where);

error_log("SQL: $sql");

        $sth = $this->dbh->prepare($sql);
        
        $sth->execute();
        
        return array(
            goods  => $sth->fetchAll(),
            count   => $sth->rowCount()
        );
        
    } 	
 }
?>
